package com.nebula.common.datasource.mybatis.db;



import com.nebula.common.datasource.mybatis.db.ds.DynamicDataSource;
import com.nebula.common.datasource.mybatis.db.ds.MdataSource;
import com.nebula.common.datasource.mybatis.spring.MyBatisConfig;

import java.util.List;

/**
 * Created by Mtime on 2017/3/28.
 */
public class MybatisDB {

    private String shardName;

    private String mainName;

    public MybatisDB(String shardName,String mainName){
        this.shardName=shardName;
        this.mainName=mainName;
    }

    /**
     * 默认的时光币读写节点
     * @param key
     * @return
     */
    public MdataSource shardWrite(long key){
        return  this.shardWrite(shardName,key);
    }

    /**
     * 默认的时光币只读节点
     * @param key
     * @return
     */
    public MdataSource shardRead(long key){
        return  this.shardRead(shardName,key);
    }

    /**
     * 普通数据源
     * @param dsName
     * @return
     */
    public MdataSource ds(String dsName){
        DynamicDataSource.setDataSourceKey(dsName);
        return new MdataSource();
    }

    public MdataSource ds(){
        DynamicDataSource.setDataSourceKey(mainName);
        return new MdataSource();
    }

    /**
     * 获得shard读写节点
     * @param shardName 分库名称
     * @param key 分库key
     * @return
     */
    public MdataSource shardWrite(String shardName,long key){
        String  dsKey=null;
        List<ShardDsNode> ShardDsNodes= MyBatisConfig.shardDsNodes;
        for (ShardDsNode shardDsNode:ShardDsNodes) {
            if (shardName.equals(shardDsNode.getShardName())&&
                    key>=shardDsNode.getStart()&&
                    key<=shardDsNode.getEnd()&&
                    shardDsNode.getType().equals("write")&&
                    key%shardDsNode.getMod()==shardDsNode.getRemainders()){
                dsKey=shardDsNode.getDsKey();
                break;
            }
        }
        DynamicDataSource.setDataSourceKey(dsKey);
        return new MdataSource();
    }

    /**
     * 获得shard只读节点
     * @param shardName 分库名称
     * @param key 分库key
     * @return
     */
    public MdataSource shardRead(String shardName,long key){
        String  dsKey=null;
        List<ShardDsNode> shardDsNodes= MyBatisConfig.shardDsNodes;
        for (ShardDsNode shardDsNode:shardDsNodes) {
            if (shardName.equals(shardDsNode.getShardName())&&
                    key>=shardDsNode.getStart()&&
                    key<=shardDsNode.getEnd()&&
                    shardDsNode.getType().equals("read")&&
                    key%shardDsNode.getMod()==shardDsNode.getRemainders()){
                dsKey=shardDsNode.getDsKey();
                break;
            }
        }
        DynamicDataSource.setDataSourceKey(dsKey);
        return new MdataSource();
    }


}
